/*
 * encoder.cpp
 *
 *  Created on: 12.05.2013
 *      Author: Roma Jam
 */

#include "encoder.h"


Encoder_t Encoder;

void Encoder_t::Task(){
	if(Delay.Elapsed(&Timer, MEAN_TIME)){
		if(LastCnt != *PCnt){
			Changed = true;
			LastCnt = *PCnt;
		}
	}
}

void Encoder_t::Init(){
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);

	klPinSetup(GPIOA, 9, pmInPullUp, ps50MHz);
	klPinSetup(GPIOA, 8, pmInPullUp, ps50MHz);

	TIM_ICInitTypeDef TIM_ICInitStructure;
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1 | TIM_Channel_2;
	TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
	TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling;
	TIM_ICInitStructure.TIM_ICFilter = 0x0;
	TIM_ICInit(TIM1, &TIM_ICInitStructure);
	TIM_EncoderInterfaceConfig(TIM1, TIM_EncoderMode_TI12, TIM_ICPolarity_Falling, TIM_ICPolarity_Falling);
	TIM_SetCounter(TIM1, 20000);
	TIM_Cmd(TIM1, ENABLE);

	PCnt = (uint32_t *) &TIM1->CNT;
	LastCnt = *PCnt;
	Changed = false;
}
